package com.sanjiahantang.youjiaclient.module.programmeprice.presenters;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.google.gson.Gson;
import com.sanjiahantang.uilibrary.utils.Utils;
import com.sanjiahantang.youjiaclient.base.BaseApplication;
import com.sanjiahantang.youjiaclient.base.BaseBean;
import com.sanjiahantang.youjiaclient.base.BaseMvpActivity;
import com.sanjiahantang.youjiaclient.base.BaseMvpPresenter;
import com.sanjiahantang.youjiaclient.base.BaseView;
import com.sanjiahantang.youjiaclient.base.CallBack;
import com.sanjiahantang.youjiaclient.config.ConfigValue;
import com.sanjiahantang.youjiaclient.config.SPConfig;
import com.sanjiahantang.youjiaclient.module.common.beans.StringBean;
import com.sanjiahantang.youjiaclient.module.common.beans.StringCheckBean;
import com.sanjiahantang.youjiaclient.module.common.views.impl.WebActivity;
import com.sanjiahantang.youjiaclient.module.me.address.beans.AddressBean;
import com.sanjiahantang.youjiaclient.module.me.contract.models.IContractModel;
import com.sanjiahantang.youjiaclient.module.me.contract.models.impl.ContractModel;
import com.sanjiahantang.youjiaclient.module.me.order.models.IOrderModel;
import com.sanjiahantang.youjiaclient.module.me.order.models.impl.OrderModel;
import com.sanjiahantang.youjiaclient.module.programmeprice.adapters.ProgramAdapter;
import com.sanjiahantang.youjiaclient.module.programmeprice.adapters.ProgramBeSureAdapter;
import com.sanjiahantang.youjiaclient.module.programmeprice.beans.ProgramAddOrderListBean;
import com.sanjiahantang.youjiaclient.module.programmeprice.beans.ProgramBean;
import com.sanjiahantang.youjiaclient.module.programmeprice.beans.ProgramContractBean;
import com.sanjiahantang.youjiaclient.module.programmeprice.beans.ProgramOrderListBean;
import com.sanjiahantang.youjiaclient.module.programmeprice.modles.IProgramPriceModel;
import com.sanjiahantang.youjiaclient.module.programmeprice.modles.impl.ProgramPriceModel;
import com.sanjiahantang.youjiaclient.module.programmeprice.views.ProgramPriceView;
import com.sanjiahantang.youjiaclient.module.programmeprice.views.impl.ProgramAddOrderActivity;
import com.sanjiahantang.youjiaclient.module.programmeprice.views.impl.ProgramChoiceInfoActivity;
import com.sanjiahantang.youjiaclient.module.programmeprice.views.impl.ProgramOrderActivity;
import com.sanjiahantang.youjiaclient.utils.SPUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



/**
 * Created by admin on 2017/10/25.
 */

public class ProgramPricePresenter extends BaseMvpPresenter<ProgramPriceView> {
    private BaseView.OnLoadListener onLoadListener;
    private BaseView.OnLoadListener listener;
    private IProgramPriceModel programPriceModel;
    private ProgramBean.Data allData, commitData;
    private ProgramAdapter adapter;
    private ProgramBeSureAdapter mAdapter;
    private IOrderModel orderModel;
    private IContractModel contractModel;

    public ProgramPricePresenter() {
        programPriceModel = new ProgramPriceModel();
        orderModel = new OrderModel();
        contractModel = new ContractModel();
    }

    //增项报价清单
    public void addPriceLoadBaoJList(final Context context, String orderCode, final BaseView.OnLoadListener listener) {
        Map<String, Object> map = new HashMap<>();
        map.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        map.put("orderCode", orderCode);
        mView.showProgress();
        programPriceModel.addPriceOnLoadBaoJList(context, map, new CallBack<ProgramAddOrderListBean>() {
            @Override
            public void onSuccess(ProgramAddOrderListBean response, Context context, Object tag) {
                if (mView == null) return;
                mView.hideProgress();
                if (response != null) {
                    listener.onLoad(response.getData());
                } else {
                    Utils.showToast(context, "订单列表获取失败");
                    ((Activity) context).finish();
                }
            }

            @Override
            public void onFailure(String message) {
                if (mView == null) return;
                mView.hideProgress();
                Utils.showToast(context, "订单列表获取失败");
                ((Activity) context).finish();
            }
        });
    }

    //报价详情加载数据
    public void LoadBaoJList(Context context, String required_id, String version, int type) {
        Map<String, Object> map = new HashMap<>();
        map.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        map.put("ppId", required_id);
        map.put("version", version);
        map.put("type", type);
        mView.showProgress();
        programPriceModel.OnLoadBaoJList(context, map, new CallBack<ProgramBean>() {
            @Override
            public void onSuccess(ProgramBean response, Context context, Object tag) {
                if (mView == null) return;
                mView.hideProgress();
                if (response.getCode() == RESPONSE_CODE_SUC) {
                    if (response.getData() != null) {
                        adapter = new ProgramAdapter(context, onLoadListener);
                        adapter.setData(response.getData());
                        adapter.setChangeData("first");
                        Object[] obj = new Object[2];
                        obj[0] = CALLBACK_TYPE_RECYCLER_ADAPTER;
                        obj[1] = adapter;
                        onLoadListener.onLoad(obj);


                    }
                }
            }

            @Override
            public void onFailure(String message) {
                if (mView == null) return;
                mView.hideProgress();
            }
        });
    }

    public void setOnLoadListener(BaseView.OnLoadListener listener) {
        onLoadListener = listener;
    }

    //保存客户下单信息
    public void savePlanPriceInfo(Context context) {
        adapter.setChangeData("3");
        allData = new ProgramBean.Data();
        List<ProgramBean.Data.ServiceListBean> serviceList = new ArrayList<>();
        List<ProgramBean.Data.GoodsListBean> materialList = new ArrayList<>();
        List<ProgramBean.Data.GoodsListBean> furnitureList = new ArrayList<>();
        List<ProgramBean.Data.GoodsListBean> accessoriesList = new ArrayList<>();

        for (int i = 0; i < adapter.getData().getServiceList().size(); i++) {
            serviceList.add(adapter.getData().getServiceList().get(i));
        }
        allData.setServiceList(serviceList);
        for (int i = 0; i < adapter.getData().getFurnitureList().size(); i++) {

            furnitureList.add(adapter.getData().getFurnitureList().get(i));

        }
        allData.setFurnitureList(furnitureList);
        for (int i = 0; i < adapter.getData().getMaterialList().size(); i++) {
            materialList.add(adapter.getData().getMaterialList().get(i));
        }
        allData.setMaterialList(materialList);
        for (int i = 0; i < adapter.getData().getAccessoriesList().size(); i++) {
            accessoriesList.add(adapter.getData().getAccessoriesList().get(i));
        }
        allData.setAccessoriesList(accessoriesList);
        allData.setToken(ConfigValue.DATA_KEY);
        // allData.setPpId(ppid);
        programPriceModel.SavePricePlanInfo(context, allData, new CallBack<StringBean>() {
            @Override
            public void onSuccess(StringBean response, Context context, Object tag) {
                if (mView == null) return;
                mView.hideProgress();
                Utils.showToast(context, "保存成功");
                Log.e("tag", "" + response.getCode() + response.getMessage());
            }

            @Override
            public void onFailure(String message) {
                if (mView == null) return;
                mView.hideProgress();
            }
        });

    }

    //去结算检查版本是否过期
    public void checkVersion(Context context, final String ppId, final int type, final String version) {
        Map<String, Object> map = new HashMap<>();
        map.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        map.put("ppId", ppId);
        programPriceModel.checkVersionInfo(context, map, new CallBack<StringCheckBean>() {
            @Override
            public void onSuccess(StringCheckBean response, Context context, Object tag) {
                if (mView == null) return;
                mView.hideProgress();
                if (response.getData().getState().equals("true")) {
                    if (response.getCode() == RESPONSE_CODE_SUC) {
                        context.startActivity(new Intent(context, ProgramChoiceInfoActivity.class)
                                .putExtra(KEY_ID, ppId)
                                .putExtra(KEY_TYPE, type)
                                .putExtra(KEY_VERSION, version)
                        );
                        BaseApplication.addActivity((Activity) context);
                        //  ((BaseMvpActivity)context).finish();
                    } else {
                        Utils.showToast(context, "已经下单更新信息");
                        //刷新当前页面
                        Object[] objects = new Object[2];
                        objects[0] = ProgramPriceView.REFRESH_THIS;
                        onLoadListener.onLoad(objects);
                    }
                }
            }

            @Override
            public void onFailure(String message) {
                if (mView == null) return;
                mView.hideProgress();
            }
        });

    }

    public void changData(Context context, String status) {
        adapter.setChangeData(status);
    }

    //查询待下单信息
    public void findPlaceOrder(Context context, int ppId, final int type) {
        Map<String, Object> map = new HashMap<>();
        map.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        map.put("ppId", ppId);
        map.put("type", type);
        mView.showProgress();
        programPriceModel.findPlaceOrder(context, map, new CallBack<ProgramBean>() {
            @Override
            public void onSuccess(ProgramBean response, Context context, Object tag) {
                if (mView == null) return;
                mView.hideProgress();
                if (response != null && response.getCode() == RESPONSE_CODE_SUC) {
                    commitData = new ProgramBean.Data();
                    if (response.getData() != null) {
                        mAdapter = new ProgramBeSureAdapter(context,type, onLoadListener);
                        mAdapter.setData(response.getData());
                        commitData = response.getData();
                        Object[] obj = new Object[2];
                        obj[0] = CALLBACK_TYPE_RECYCLER_ADAPTER;
                        obj[1] = mAdapter;
                        onLoadListener.onLoad(obj);

                        Object[] objData = new Object[2];
                        objData[0] = CALLBACK_TYPE_ORDER_DATA;
                        objData[1] = response.getData();
                        onLoadListener.onLoad(objData);
                    }

                    searchUserAddressOrder(context);
                }
            }

            @Override
            public void onFailure(String message) {
                if (mView == null) return;
                mView.hideProgress();
            }
        });
    }

    private void searchUserAddressOrder(Context context) {
        Map<String, String> params = new HashMap<>();
        params.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        params.put(KEY_PHONE, SPUtils.get(context, SPConfig.PHONE, "").toString());
        mView.showProgress();
        orderModel.searchUserAddressOrder(context, params, new CallBack<AddressBean>() {
            @Override
            public void onSuccess(AddressBean response, Context context, Object tag) {
                if (mView == null) return;
                mView.hideProgress();
                if (response.getCode() == RESPONSE_CODE_SUC && response.getData().size() > 0) {
                    Object[] obj = new Object[2];
                    obj[0] = CALLBACK_TYPE_ADDRESS;
                    obj[1] = response.getData().get(0);
                    onLoadListener.onLoad(obj);
                }

            }

            @Override
            public void onFailure(String message) {
                if (mView == null) return;
                mView.hideProgress();
            }
        });
    }

    //提交订单
    public void creatOrderPhoneForPlan(final Context context,
                                       int addressId, final int ppId, final String message, final int type) {
        mView.showProgress();
        commitData.setToken(ConfigValue.DATA_KEY);
        commitData.setUserAddressId(addressId);
        commitData.setPhoneTypeId(0);
        commitData.setBuyPersonMessage(message);
        commitData.setType(type);
        programPriceModel.creatOrderPhoneForPlan(context, commitData, ppId, type, new CallBack<StringBean>() {
            @Override
            public void onSuccess(StringBean response, Context context, Object tag) {
                if (mView == null) return;
                mView.hideProgress();
                if (response != null && response.getCode() == RESPONSE_CODE_SUC) {
                    Utils.showToast(context, "提交成功");
                    if (type == ProgramPriceView.TYPE_INCREASE) {//跳转增项清单
                        ProgramAddOrderListBean.Data programAddOrderListBean = new Gson().fromJson(response.getData(), ProgramAddOrderListBean.Data.class);
                        context.startActivity(new Intent(context, ProgramAddOrderActivity.class)
                                .putExtra(KEY_ID, programAddOrderListBean.getOrderCode())
                                .putExtra(KEY_TYPE, type));
                        BaseApplication.clearActivity();
                        ((BaseMvpActivity) context).finish();
                    } else {
                        context.startActivity(new Intent(context, ProgramOrderActivity.class)
                                .putExtra(KEY_ID, ppId)
                                .putExtra(KEY_TYPE, type));
                        BaseApplication.clearActivity();
                        ((BaseMvpActivity) context).finish();
                    }

//                    //提交成功后更新版本
//                    Map<String, String> map = new HashMap<String, String>();
//                    map.put("ppId", String.valueOf(ppId));
//                    map.put(KEY_TOKEN, ConfigValue.DATA_KEY);
//                    map.put("type", "0");
                    //                  programPriceModel.updateProjectPriceInfoIsPlaceAnOrder(context, map, new CallBack<StringBean>() {
//                        @Override
//                        public void onSuccess(StringBean response, Context context, Object tag) {
//                            Utils.showToast(context,"提交成功");
//                        }
//                        @Override
//                        public void onFailure(String message) {
//                        }
//                    });
                } else {
                    Utils.showToast(context, "提交失败了" + ((response == null) ? "" : (" , 原因:" + response.getMessage())));
                }
            }

            @Override
            public void onFailure(String message) {
                if (mView == null) return;
                mView.hideProgress();
                Utils.showToast(context, "提交失败了" + ((message == null) ? "" : (" , -- " + message)));
            }
        });
    }

    public void indexContractInfo(final Context context, final BaseView.OnLoadListener listener) {
        mView.showProgress();
        Map<String, String> param = new HashMap<>();
        param.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        param.put(KEY_PHONE, SPUtils.get(context, SPConfig.PHONE, "").toString());
        contractModel.indexContractInfo(context, param, new CallBack<BaseBean>() {
            @Override
            public void onSuccess(BaseBean response, Context context, Object tag) {
                if (mView == null) return;
                mView.hideProgress();
                if (response != null && response.getCode() == RESPONSE_CODE_SUC) {
                    if (tag instanceof ProgramContractBean.Data) {
                        ProgramContractBean.Data data = (ProgramContractBean.Data) tag;
                        listener.onLoad(data);
                        String param = "contractCode=" + data.getContractCode() + "&signer=" + data.getSigner1();
                        ((Activity) context).startActivityForResult(new Intent(context, WebActivity.class)
                                        .putExtra(KEY_TYPE, WEB_TYPE_CONTRACT).putExtra(KEY_PARAM, param)
                                , 2);
                    } else {
                        Utils.showToast(context, "签署合同失败");
                    }
                } else {
                    Utils.showToast(context, "签署合同失败");
                }
            }

            @Override
            public void onFailure(String message) {
                if (mView == null) return;
                mView.hideProgress();
                Utils.showToast(context, "签署合同失败");
            }
        });
    }

    public void saveContractForPhoneProject(final Context context, ProgramContractBean.Data contractData, float contractPrice, ProgramBean.Data programData, final BaseView.OnLoadListener listener) {
        Map<String, Object> param = new HashMap<>();
        param.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        param.put("pcId", contractData.getPcId());
        param.put("contractCode", contractData.getContractCode());
        param.put("userRequireId", commitData.getUserRequireId());
        param.put("customerPhone", SPUtils.get(context, SPConfig.PHONE, "").toString());
        if (programData.getUserName() == null) {
            Utils.showToast(context, "获取客户姓名失败");
            return;
        }
        param.put("customerName", programData.getUserName());
        param.put("contractPrice", contractPrice);
        param.put("signer2", contractData.getSigner1());
        mView.showProgress();
        contractModel.saveContractForPhoneProject(context, param, new CallBack<BaseBean>() {
            @Override
            public void onSuccess(BaseBean response, Context context, Object tag) {
                if (mView == null) return;
                mView.hideProgress();
                if (response != null && response.getCode() == RESPONSE_CODE_SUC) {
                    listener.onLoad(response);
                } else {
                    Utils.showToast(context, "合同保存失败了");
                }
            }

            @Override
            public void onFailure(String message) {
                if (mView == null) return;
                mView.hideProgress();
                Utils.showToast(context, "合同保存失败了");
            }
        });
    }

    public void findPlanInfo(final Context context, int ppId, final BaseView.OnLoadListener listener) {
        Map<String, String> param = new HashMap<>();
        param.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        param.put("ppId", String.valueOf(ppId));
        mView.showProgress();
        programPriceModel.findPlanInfo(context, param, new CallBack<ProgramOrderListBean>() {
            @Override
            public void onSuccess(ProgramOrderListBean response, Context context, Object tag) {
                if (mView == null) return;
                mView.hideProgress();
                if (response != null && response.getCode() == RESPONSE_CODE_SUC) {
                    listener.onLoad(response.getData());
                } else {
                    Utils.showToast(context, "订单列表获取失败");
                    ((Activity) context).finish();
                }
            }

            @Override
            public void onFailure(String message) {
                if (mView == null) return;
                mView.hideProgress();
                Utils.showToast(context, "订单列表获取失败");
                ((Activity) context).finish();
            }
        });
    }
}
